package org.sky.component.excel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtil {
	/**导出
	 * @param sheetName
	 * @param head
	 * @param data
	 * @param path
	 * @param fileOutStream
	 */
	public static void toExcel(String sheetName,String [] head,List <List<String>> data,String path,FileOutputStream fileOutStream){
		HSSFWorkbook workbook = new HSSFWorkbook(); //产生工作簿对象
		HSSFSheet sheet = workbook.createSheet(); //产生工作表对象
		//行对象
		HSSFRow row;
		//单元格对象
		HSSFCell cell;
		workbook.setSheetName(0,sheetName);
		//添加表头
		row= sheet.createRow(0);
		for (int i = 0; i < head.length; i++) {
			cell = row.createCell(i);
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(head[i]);
		}
		//添加数据
		for(int j=0;j<data.size();j++){
			row= sheet.createRow(j+1);
			List cellList=data.get(j);
			for (int z=0;z<cellList.size();z++) {
				cell = row.createCell(z);
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue((String)cellList.get(z));
			}
		}
		//导出excel
		try {
			FileOutputStream fOut = null;
			if(path!=null){
				fOut = new FileOutputStream(path);
			}else if(fileOutStream!=null){
				fOut=fileOutStream;
			}
			workbook.write(fOut);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
		
	public static void main(String[] args) {
		List  list1= new ArrayList<String>();
		List  list2= new ArrayList<List>();
		list1.add("123");
		list1.add("123");
		list1.add("123");
		list2.add(list1);
		list2.add(list1);
		list2.add(list1);
		ExcelUtil.toExcel("bb", new String[]{"aa","bb"},list2,"D://t2.xls",null);
	}
}
